import constants, math, time, data, pickle

class Score(object):
    """Understands a character's score"""
    
    def __init__(self):
        self._number = 0
        self._old_str = None
        self._old_height = 0
        
    def num(self):
        return self._number
        
    def update(self, str = None, height = 0):
        if self._old_height < height:
            self._old_height = height
            self._number += int(math.floor(height * constants.SCORE_RATIO))
        
        if str != None and self._old_str != str:
            self._old_str = str
            self._number += constants.ATTACH_BONUS

    @staticmethod
    def get_highest_score():
        try:
            scores_file = data.load(constants.SCORES_FILE, 'r')
            scores_dic = pickle.load(scores_file)
        except:
            return 0

        for date, high_score in scores_dic.items():
            #self.log.debug("date and score: %s = %s" % (date, high_score))
            return int(high_score)

    def is_new_high_score(self):
        if self.num() > Score.get_highest_score(): return True
        return False

    def save(self):
        try:
            scores_file = data.load(constants.SCORES_FILE, 'a')
            scores_dic = pickle.load(scores_file)
        except:
            pass
            #self.log.debug("No score file yet")

        scores = { now() : self.num() }
        scores_file = data.load(constants.SCORES_FILE, 'w')
        pickle.dump(scores, scores_file)

    def __str__(self):
        return str(self.num())

def now():
    return time.strftime("%h %d %H:%M")

